import store from "./store/index.js";

import { addAction, subAction, incAction } from "./store/actionCreators.js";

store.subscribe(() => {
  console.log(store.getState());
})


// 基本做法
// console.log('dispatch前---dispatching：Action',addAction(10));
// store.dispatch(addAction(10))
// console.log('dispatch后---new state',store.getState());

// console.log('dispatch前---dispatching：Action',addAction(15));
// store.dispatch(addAction(15))
// console.log('dispatch后---new state',store.getState());
// const next = store.dispatch
// 封装一个函数
// function dispatchAndLogging(action) {
//   console.log('dispatch前---dispatching：Action', action);
//   next(action)
//   console.log('dispatch后---new state', action);
// }
// store.dispatch = dispatchAndLogging

// 4.将之前的操作进行封装
// 封装patchLogging的代码
function patchLogging(store) {
  const next = store.dispatch;
  function dispatchAndLogging(action) {
    console.log("dispatch前---dispatching action:", action);
    next(action);
    console.log("dispatch后---new state:", store.getState());
  }
  // store.dispatch = dispatchAndLogging;

  return dispatchAndLogging;
}


function pathchThunk(store) {
  const next = store.dispatch
  function dispatchAndThunk(action) {
    if(typeof action === 'function') {
      action(store.dispatch,store.getState)
    }else {
      next(action)
    }
  }
  store.dispatch = dispatchAndThunk
}

patchLogging(store);
pathchThunk(store)

// function foo (dispatch,getState) {
//   // console.log(dispatch,getState);
//   dispatch(subAction(10))
// }
// store.dispatch(foo)
// store.dispatch(addAction(10))
// store.dispatch(addAction(5))

// 5.封装applyMiddleware
function applyMiddlewares(...middlewares) {
  middlewares.forEach(middleware =>{
    store.dispatch=middleware(store)
  })
}
pathchThunk(store)
applyMiddlewares(patchLogging,)